// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.XmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.mapper.KdlSaleOutBMapper;
import com.javaweb.admin.mapper.KdlSaleOutMapper;
import com.javaweb.admin.query.KdlSaleOutQuery;
import com.javaweb.admin.service.IKdlSaleOutService;
import com.javaweb.admin.service.INcServiceLogService;
import com.javaweb.admin.vo.kdlsaleout.KdlSaleOutInfoVo;
import com.javaweb.admin.vo.kdlsaleout.KdlSaleOutListVo;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.javaweb.common.utils.StringUtils;
import com.seegw.shaphar.DDKJConfig;
import com.seegw.shaphar.KDLConfig;
import com.seegw.shaphar.KDLRequest;
import com.sphsine.bip.SHYPConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 销售出库 服务类实现
 * </p>
 *
 * @author 鲲鹏
 * @since 2024-01-27
 */
@Service
public class KdlSaleOutServiceImpl extends BaseServiceImpl<KdlSaleOutMapper, KdlSaleOut> implements IKdlSaleOutService {

    @Autowired
    private KdlSaleOutMapper kdlSaleOutMapper;


    @Autowired
    private KdlSaleOutBMapper kdlSaleOutBMapper;

    @Autowired
    INcServiceLogService ncServiceLogService;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getList(BaseQuery query) {
        KdlSaleOutQuery kdlSaleOutQuery = (KdlSaleOutQuery) query;
        // 查询条件
        QueryWrapper<KdlSaleOut> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");

        // 获取数据列表
        IPage<KdlSaleOut> page = new Page<>(kdlSaleOutQuery.getPage(), kdlSaleOutQuery.getLimit());
        IPage<KdlSaleOut> pageData = kdlSaleOutMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            KdlSaleOutListVo kdlSaleOutListVo = Convert.convert(KdlSaleOutListVo.class, x);
            return kdlSaleOutListVo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public Object getInfo(Serializable id) {
        KdlSaleOut entity = (KdlSaleOut) super.getInfo(id);
        // 返回视图Vo
        KdlSaleOutInfoVo kdlSaleOutInfoVo = new KdlSaleOutInfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, kdlSaleOutInfoVo);
        return kdlSaleOutInfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult edit(KdlSaleOut entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
        } else {
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult delete(KdlSaleOut entity) {
        entity.setMark(0);
        return super.delete(entity);
    }

    /*
     * 获取康德乐销售出库
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncSaleOut(KdlSaleOutQuery query) {

        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + query.getPrincipalid() + "</PrincipalID>");
            sb.append("<DocType>" + query.getDoctype() + "</DocType>");
            sb.append("<StartTime>" + kdlSaleOutMapper.GetMaxSyncTime() + "</StartTime>");
            sb.append("<EndTime>" + DateUtils.getTime() + "</EndTime>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid() + "_" + query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                log.setResponseBody(result);
                ncServiceLogService.save(log);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlSaleOutDto dto = new KdlSaleOutDto();
                        KdlSaleOut saleOut = new KdlSaleOut();
                        KdlSaleOutB saleOutB = new KdlSaleOutB();
                        saleOut.setPrincipalid(CommonUtils.XmlGetNodeContent(headResult, "PrincipalID"));
                        saleOut.setPrincipalname(CommonUtils.XmlGetNodeContent(headResult, "PrincipalName"));
                        saleOut.setVendorso(CommonUtils.XmlGetNodeContent(headResult, "VendorSO"));
                        saleOut.setDoctype(CommonUtils.XmlGetNodeContent(headResult, "DocType"));
                        String pgiDate = DateUtil.format(DateUtil.parse(CommonUtils.XmlGetNodeContent(headResult, "PGIDate"), DateUtils.YYYYMMDD), DateUtils.YYYY_MM_DD);
                        saleOut.setPgidate(pgiDate);
                        saleOut.setCustomername(CommonUtils.XmlGetNodeContent(headResult, "CustomerName"));
                        saleOut.setDeliveryaddress(CommonUtils.XmlGetNodeContent(headResult, "DeliveryAddress"));
                        saleOut.setPlantaddress(CommonUtils.XmlGetNodeContent(headResult, "PlantAddress"));
                        saleOut.setPgiid(CommonUtils.XmlGetNodeContent(headResult, "PGIID"));
                        saleOut.setPgiidname(CommonUtils.XmlGetNodeContent(headResult, "PGIIDName"));
                        if (kdlSaleOutMapper.selectOne(new QueryWrapper<KdlSaleOut>().eq("vendorso", saleOut.getVendorso())) == null) {
                            kdlSaleOutMapper.insert(saleOut);
                        } else {
                            saleOut.setUpdateTime(DateUtils.now());
                            kdlSaleOutMapper.update(saleOut, new UpdateWrapper<KdlSaleOut>().eq("vendorso", saleOut.getVendorso()));
                        }
                        //遍历明细Details
                        Element detail = null;
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            saleOutB.setVendorso(saleOut.getVendorso());
                            saleOutB.setCahdnno(CommonUtils.XmlGetNodeContent(detail, "CAHDNNO"));
                            saleOutB.setVendorsolineno(CommonUtils.XmlGetNodeContent(detail, "VendorSOLineNo"));
                            saleOutB.setVendordnlineno(CommonUtils.XmlGetNodeContent(detail, "VendorDNLineNo"));
                            saleOutB.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            saleOutB.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            saleOutB.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            saleOutB.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            saleOutB.setMaterialdes(CommonUtils.XmlGetNodeContent(detail, "MaterialDes"));
                            saleOutB.setComdescription(CommonUtils.XmlGetNodeContent(detail, "ComDescription"));
                            saleOutB.setMaterialspec(CommonUtils.XmlGetNodeContent(detail, "MaterialSpec"));
                            saleOutB.setMaterialform(CommonUtils.XmlGetNodeContent(detail, "MaterialForm"));
                            saleOutB.setRegistno(CommonUtils.XmlGetNodeContent(detail, "RegistNo"));
                            saleOutB.setManufacturername(CommonUtils.XmlGetNodeContent(detail, "ManufacturerName"));
                            saleOutB.setSubmaufacturername(CommonUtils.XmlGetNodeContent(detail, "SubMaufacturerName"));
                            saleOutB.setVendorissueplant(CommonUtils.XmlGetNodeContent(detail, "VendorIssuePlant"));
                            saleOutB.setCahissueplant(CommonUtils.XmlGetNodeContent(detail, "CAHIssuePlant"));
                            saleOutB.setOrderqty(CommonUtils.XmlGetNodeContent(detail, "OrderQty", 0));
                            saleOutB.setPgiquantity(CommonUtils.XmlGetNodeContent(detail, "PGIQuantity", 0));
                            saleOutB.setCahuom(CommonUtils.XmlGetNodeContent(detail, "CAHUOM"));
                            saleOutB.setVendoruom(CommonUtils.XmlGetNodeContent(detail, "VendorUOM"));
                            saleOutB.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            saleOutB.setSerialno(CommonUtils.XmlGetNodeContent(detail, "SerialNo"));
                            saleOutB.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            saleOutB.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            saleOutB.setSterilizationbatch(CommonUtils.XmlGetNodeContent(detail, "SterilizationBatch"));
                            saleOutB.setRecheckdate(CommonUtils.XmlGetNodeContent(detail, "ReCheckDate"));
                            saleOutB.setRecheckidname(CommonUtils.XmlGetNodeContent(detail, "RecheckIDName"));
                            saleOutB.setCahlocation(CommonUtils.XmlGetNodeContent(detail, "CAHlocation"));
                            saleOutB.setSyncTime(CommonUtils.XmlGetNodeContent(detail, "Time"));
                            try {
                                KdlSaleOutB storeInfo = kdlSaleOutMapper.getStoreInfo(saleOutB.getVendordnlineno());
                                saleOutB.setStorcode(storeInfo.getStorcode());
                                saleOutB.setStorname(storeInfo.getStorname());
                            } catch (Exception e) {

                            }

                            KdlSaleOutB selectOne = kdlSaleOutBMapper.selectOne(new QueryWrapper<KdlSaleOutB>().eq("vendorso", saleOutB.getVendorso())
                                    .eq("vendorsolineno", saleOutB.getVendorsolineno())
                                    .eq("vendordnlineno", saleOutB.getVendordnlineno()));
                            if (selectOne == null) {
                                kdlSaleOutBMapper.insert(saleOutB);
                            } else {
                                saleOutB.setUpdateTime(DateUtils.now());
                                kdlSaleOutBMapper.update(saleOutB, new UpdateWrapper<KdlSaleOutB>().eq("vendorso", saleOutB.getVendorso())
                                        .eq("vendorsolineno", saleOutB.getVendorsolineno())
                                        .eq("vendordnlineno", saleOutB.getVendordnlineno()));
                            }
                        }
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString()) ? JsonResult.success() : JsonResult.error(sbResult.toString());
            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);
            }
        } catch (
                Exception ex) {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getDetailsByVendorso(String vendorso) {
        return JsonResult.success(kdlSaleOutBMapper.getDetailsByVendorso(vendorso));
    }
}
































